package com.qiao.glod.bean;

import android.util.Log;

import com.qiao.glod.api.Constants;
import com.qiao.glod.api.GoldApi;
import com.qiao.glod.api.ICallback;
import com.qiao.glod.application.QApplication;
import com.qiao.glod.util.LocalRequestManager;
import com.qiao.glod.util.task.async.TaskExecutor;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.ModelContainer;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.BaseModel;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Qiao on 2016/4/16.
 * function：
 */
@ModelContainer
@Table(database  = GoldDatabase.class, useIsForPrivateBooleans = true)
public class GiftBean extends BaseModel {

    /**
     * _id : 57105e6e67765974f885bef9
     * createdAt : 2016-04-15T11:22:22.754Z
     * desc : 基于 Facebook Redex 实现 Android APK 的压缩和优化
     * publishedAt : 2016-04-15T13:04:43.738Z
     * source : chrome
     * type : Android
     * url : http://mp.weixin.qq.com/s?__biz=MzAwMTYwNzE2Mg==&mid=2651036594&idx=1&sn=b276c0f76cea713e5d568ab51e3f7f13&scene=0#wechat_redirect
     * used : true
     * who : MVP
     */

    @PrimaryKey
    private String _id;
    @Column
    private String createdAt;
    @Column
    private String desc;
    @Column
    private String publishedAt;
    @Column
    private String source;
    @Column
    private String type;
    @Column
    private String url;
    @Column
    private boolean used;
    @Column
    private String who;
    @Column
    private String img;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public boolean isUsed() {
        return used;
    }

    public void setUsed(boolean used) {
        this.used = used;
    }

    public String getWho() {
        return who;
    }

    public void setWho(String who) {
        this.who = who;
    }

    public String getImg() {
        return img;
    }

    public void setImg(String img) {
        this.img = img;
    }

    public static List<GiftBean> getGitfs(String type,int limit,int page){
        if(!Constants.DataType.All.equals(type)){
            return SQLite.select()
                    .from(GiftBean.class)
                    .where(GiftBean_Table.type.eq(type))
                    .limit(limit)
                    .offset(limit*(page-1))
                    .queryList();
        }else{
            return SQLite.select()
                    .from(GiftBean.class)
                    .limit(limit)
                    .offset(limit*(page-1))
                    .queryList();
        }
    }

    public static void loadOnLine(final String type,int limit,final int page, ICallback<List<GiftBean>> callback){
        Log.i("loadOnLine", "loadOnLine:.................... "+type+page);
        if(!LocalRequestManager.getInstance().isNewRequest(page,callback)) return;
        Log.e("loadOnLine", "isNewRequest............");

        GoldApi.getGankApi().getGifts(limit,page)
                .enqueue(new Callback<Results>() {
                    @Override
                    public void onResponse(Call<Results> call, Response<Results> response) {
                        if(response.isSuccessful()){
                            results = response.body();
                            Log.i("getGifts---","onResponse：" + results.toString());
                            wrap(type,page);
                        }
                    }

                    @Override
                    public void onFailure(Call<Results> call, Throwable t) {
                        Log.e("Error:getGifts---","Message：" + t.getMessage());
                        LocalRequestManager.getInstance().callback(page,t.getMessage());
                    }
                });

        GoldApi.getMeituApi().getImageList(limit,page)
                .enqueue(new Callback<ImageWarper>() {
                    @Override
                    public void onResponse(Call<ImageWarper> call, Response<ImageWarper> response) {
                        if(response.isSuccessful()){
                            warper = response.body();
                            Log.i("getImageList---","onResponse：" + response.toString());
                            wrap(type,page);
                        }
                    }

                    @Override
                    public void onFailure(Call<ImageWarper> call, Throwable t) {
                        Log.e("Error:getImageList---","Message：" + t.getMessage());
                        LocalRequestManager.getInstance().callback(page,t.getMessage());
                    }
                });
    }

    static Results results;
    static ImageWarper warper;
    public static void wrap(final String type,final int page){
        if(results==null || warper==null) return;//数据未加载完成

        if(results.isError() || !warper.isStatus() ) {
            LocalRequestManager.getInstance().callback(page,"数据获取失败！");
            return;
        }

        TaskExecutor.start(new Runnable() {
            @Override
            public void run() {

                int i = 0;
                for(GiftBean bean:results.getResults()){
                    bean.setImg(warper.getTngou().get(i++).getImg());
                    bean.save();
                }

                QApplication.uiHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        LocalRequestManager.getInstance().callback(page,results.getResults());
                        results = null;
                        warper = null;
                    }
                });
            }
        });
    }
}
